<template>
  <view class="realtime-stats">
    <view class="section-header">
      <text class="section-title">实时数据统计</text>
      <view class="update-info">
        <text class="update-time">{{ getUpdateTime() }}</text>
        <view 
          class="refresh-btn"
          @click="handleRefresh"
          :class="{ 'refreshing': refreshing }"
        >
          <text class="refresh-icon">↻</text>
        </view>
      </view>
    </view>
    
    <view class="realtime-grid">
      <view 
        v-for="(item, index) in realtimeData" 
        :key="index" 
        class="realtime-item"
        @click="handleItemClick(item)"
      >
        <view class="realtime-header">
          <text class="realtime-label">{{ item.label }}</text>
          <view :class="['status-indicator', item.status]"></view>
        </view>
        <view class="realtime-content">
          <view class="realtime-number">{{ item.value }}</view>
          <view class="realtime-unit">{{ item.unit }}</view>
        </view>
        <view v-if="item.trend" class="trend-info">
          <text :class="['trend-text', item.trend.type]">{{ item.trend.text }}</text>
        </view>
      </view>
    </view>
    
    <!-- 详细统计卡片 -->
    <view class="detail-cards">
      <view class="detail-card">
        <view class="card-header">
          <text class="card-title">设备状态分布</text>
        </view>
        <view class="device-status-grid">
          <view 
            v-for="(status, index) in deviceStatusData" 
            :key="index" 
            class="device-status-item"
          >
            <view :class="['status-dot', status.type]"></view>
            <text class="status-label">{{ status.label }}</text>
            <text class="status-count">{{ status.count }}</text>
          </view>
        </view>
      </view>
      
      <view class="detail-card">
        <view class="card-header">
          <text class="card-title">工单类型统计</text>
        </view>
        <view class="workorder-type-grid">
          <view 
            v-for="(type, index) in workOrderTypeData" 
            :key="index" 
            class="workorder-type-item"
          >
            <view class="type-progress">
              <view 
                class="progress-bar" 
                :style="{ width: type.percentage + '%', backgroundColor: type.color }"
              ></view>
            </view>
            <view class="type-info">
              <text class="type-label">{{ type.label }}</text>
              <text class="type-count">{{ type.count }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted, defineEmits } from 'vue';
import { getRealtimeStats, getDeviceStatus, getWorkOrderStats } from '@/api';

const emit = defineEmits(['refresh']);

const realtimeData = ref([]);
const deviceStatusData = ref([]);
const workOrderTypeData = ref([]);
const lastUpdateTime = ref('');
const refreshing = ref(false);
const autoRefreshTimer = ref(null);

// 获取更新时间
const getUpdateTime = () => {
  return lastUpdateTime.value ? `更新于 ${lastUpdateTime.value}` : '暂无数据';
};

// 获取实时数据统计
const fetchRealtimeStats = async () => {
  try {
    // 暂时使用模拟数据，实际项目中调用真实API
    // const res = await getRealtimeStats();
    // const data = res.data;
    
    const mockData = {
      onlineInspectors: Math.floor(Math.random() * 30) + 20,
      abnormalDevices: Math.floor(Math.random() * 8) + 1,
      todayWorkOrders: Math.floor(Math.random() * 50) + 30,
      totalDevices: 156,
      normalDevices: 148
    };
    
    realtimeData.value = [
      {
        label: '在线巡检员',
        value: mockData.onlineInspectors,
        unit: '人',
        status: 'online',
        trend: {
          type: 'up',
          text: '↑ 2人'
        },
        path: '/pages/inspector-info/index'
      },
      {
        label: '异常设备',
        value: mockData.abnormalDevices,
        unit: '台',
        status: mockData.abnormalDevices > 5 ? 'error' : mockData.abnormalDevices > 0 ? 'warning' : 'normal',
        trend: {
          type: mockData.abnormalDevices > 3 ? 'up' : 'down',
          text: mockData.abnormalDevices > 3 ? '↑ 1台' : '↓ 2台'
        },
        path: '/pages/device-status/index'
      },
      {
        label: '今日工单总数',
        value: mockData.todayWorkOrders,
        unit: '个',
        status: 'normal',
        trend: {
          type: 'up',
          text: '↑ 5个'
        },
        path: '/pages/work-order/index'
      }
    ];
    
    // 设备状态数据
    deviceStatusData.value = [
      {
        label: '正常',
        count: mockData.normalDevices,
        type: 'normal'
      },
      {
        label: '异常',
        count: mockData.abnormalDevices,
        type: 'error'
      },
      {
        label: '离线',
        count: mockData.totalDevices - mockData.normalDevices - mockData.abnormalDevices,
        type: 'offline'
      }
    ];
    
    // 工单类型数据
    const workOrderTypes = [
      { label: '设备故障', count: Math.floor(mockData.todayWorkOrders * 0.4), color: '#f5222d' },
      { label: '设备维护', count: Math.floor(mockData.todayWorkOrders * 0.3), color: '#fa8c16' },
      { label: '巡检任务', count: Math.floor(mockData.todayWorkOrders * 0.2), color: '#52c41a' },
      { label: '其他', count: Math.floor(mockData.todayWorkOrders * 0.1), color: '#1890ff' }
    ];
    
    const maxCount = Math.max(...workOrderTypes.map(item => item.count));
    workOrderTypeData.value = workOrderTypes.map(item => ({
      ...item,
      percentage: maxCount > 0 ? (item.count / maxCount) * 100 : 0
    }));
    
    // 更新时间
    const now = new Date();
    lastUpdateTime.value = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
    
    // 通知父组件数据已更新
    emit('refresh', {
      onlineInspectors: mockData.onlineInspectors,
      abnormalDevices: mockData.abnormalDevices,
      todayWorkOrders: mockData.todayWorkOrders
    });
    
  } catch (error) {
    console.error('获取实时数据统计失败', error);
    uni.showToast({
      title: '获取数据失败',
      icon: 'none'
    });
  }
};

// 手动刷新
const handleRefresh = async () => {
  if (refreshing.value) return;
  
  refreshing.value = true;
  try {
    await fetchRealtimeStats();
    uni.showToast({
      title: '刷新成功',
      icon: 'success',
      duration: 1000
    });
  } finally {
    setTimeout(() => {
      refreshing.value = false;
    }, 1000);
  }
};

// 处理项目点击
const handleItemClick = (item) => {
  if (item.path) {
    uni.navigateTo({
      url: item.path
    });
  }
};

// 开始自动刷新
const startAutoRefresh = () => {
  if (autoRefreshTimer.value) {
    clearInterval(autoRefreshTimer.value);
  }
  
  // 每30秒自动刷新一次
  autoRefreshTimer.value = setInterval(() => {
    fetchRealtimeStats();
  }, 30000);
};

// 停止自动刷新
const stopAutoRefresh = () => {
  if (autoRefreshTimer.value) {
    clearInterval(autoRefreshTimer.value);
    autoRefreshTimer.value = null;
  }
};

// 暴露刷新方法给父组件
const refresh = () => {
  fetchRealtimeStats();
};

// 刷新数据方法（供父组件调用）
const refreshData = async () => {
  await fetchRealtimeStats();
  emit('refresh');
};

// 暴露方法
defineExpose({
  refresh,
  refreshData,
  startAutoRefresh,
  stopAutoRefresh
});

// 组件挂载时获取数据并开始自动刷新
onMounted(() => {
  fetchRealtimeStats();
  startAutoRefresh();
});

// 组件卸载时停止自动刷新
onUnmounted(() => {
  stopAutoRefresh();
});
</script>

<style lang="scss" scoped>
.realtime-stats {
  background-color: #ffffff;
  border-radius: 12rpx;
  padding: 24rpx;
  margin: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
}

.update-info {
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.update-time {
  font-size: 24rpx;
  color: #999999;
}

.refresh-btn {
  width: 48rpx;
  height: 48rpx;
  border-radius: 50%;
  background-color: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.refresh-btn.refreshing {
  animation: rotate 1s linear infinite;
}

.refresh-icon {
  font-size: 28rpx;
  color: #666666;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.realtime-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20rpx;
  margin-bottom: 24rpx;
}

.realtime-item {
  background-color: #fafafa;
  border-radius: 8rpx;
  padding: 20rpx;
  text-align: center;
  transition: transform 0.2s ease;
}

.realtime-item:active {
  transform: scale(0.95);
}

.realtime-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12rpx;
}

.realtime-label {
  font-size: 24rpx;
  color: #666666;
}

.status-indicator {
  width: 12rpx;
  height: 12rpx;
  border-radius: 50%;
}

.status-indicator.online {
  background-color: #52c41a;
  box-shadow: 0 0 8rpx rgba(82, 196, 26, 0.4);
}

.status-indicator.warning {
  background-color: #faad14;
  box-shadow: 0 0 8rpx rgba(250, 173, 20, 0.4);
}

.status-indicator.error {
  background-color: #f5222d;
  box-shadow: 0 0 8rpx rgba(245, 34, 45, 0.4);
}

.status-indicator.normal {
  background-color: #1890ff;
  box-shadow: 0 0 8rpx rgba(24, 144, 255, 0.4);
}

.realtime-content {
  margin-bottom: 8rpx;
}

.realtime-number {
  font-size: 36rpx;
  font-weight: bold;
  color: #333333;
  margin-bottom: 4rpx;
}

.realtime-unit {
  font-size: 20rpx;
  color: #999999;
}

.trend-info {
  height: 24rpx;
}

.trend-text {
  font-size: 20rpx;
}

.trend-text.up {
  color: #f5222d;
}

.trend-text.down {
  color: #52c41a;
}

/* 详细统计卡片 */
.detail-cards {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20rpx;
}

.detail-card {
  background-color: #fafafa;
  border-radius: 8rpx;
  padding: 20rpx;
}

.card-header {
  margin-bottom: 16rpx;
}

.card-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333333;
}

/* 设备状态分布 */
.device-status-grid {
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

.device-status-item {
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.status-dot {
  width: 16rpx;
  height: 16rpx;
  border-radius: 50%;
}

.status-dot.normal {
  background-color: #52c41a;
}

.status-dot.error {
  background-color: #f5222d;
}

.status-dot.offline {
  background-color: #d9d9d9;
}

.status-label {
  font-size: 24rpx;
  color: #666666;
  flex: 1;
}

.status-count {
  font-size: 24rpx;
  font-weight: bold;
  color: #333333;
}

/* 工单类型统计 */
.workorder-type-grid {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.workorder-type-item {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.type-progress {
  height: 8rpx;
  background-color: #f0f0f0;
  border-radius: 4rpx;
  overflow: hidden;
}

.progress-bar {
  height: 100%;
  border-radius: 4rpx;
  transition: width 0.3s ease;
}

.type-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.type-label {
  font-size: 24rpx;
  color: #666666;
}

.type-count {
  font-size: 24rpx;
  font-weight: bold;
  color: #333333;
}
</style>